﻿using System;
using System.Net;
using System.Threading.Tasks;
using System.IO;
using ICSharpCode.SharpZipLib.GZip;
using System.Xml.Linq;

namespace EnglishStudy.Service
{
    /// <summary>
    /// 
    /// </summary>
    public class HttpResponseMessageWrapper : IHttpResponseMessage
    {
        private readonly HttpWebResponse _httpWebResponseMessage;

        public HttpResponseMessageWrapper(HttpWebResponse httpResponseMessage)
        {
            _httpWebResponseMessage = httpResponseMessage;
        }

        public Task<string> ReadAsStringAsync()
        {
            return Task.Run(() => ReadAsString());
        }

        private string ReadAsString()
        {
            if (_httpWebResponseMessage == null)
                return string.Empty;
            string header = _httpWebResponseMessage.Headers["Content-Encoding"];
            Stream stream = _httpWebResponseMessage.GetResponseStream();

            String returnString;
            if (!string.IsNullOrEmpty(header) && header.ToLower().Contains("gzip"))
            {
                Stream streamgzip = new GZipInputStream(_httpWebResponseMessage.GetResponseStream());
                XDocument document = XDocument.Load(streamgzip);
                returnString = document.ToString();
                return returnString;
            }
           else
            {
                using(var resder=new StreamReader(stream))
                {
                    return resder.ReadToEnd();
                }
            }
        }

        public Task<byte[]> ReadAsByteArrayAsync()
        {
            return null;
        }
      
        public Task<Stream> ReadAsStreamAsync() 
        {
            return null;
        }

        public string[] GetCookies()
        {
            if (_httpWebResponseMessage == null)
                return null;
            string cookCollect = _httpWebResponseMessage.Headers["Set-Cookie"];

            if (string.IsNullOrEmpty(cookCollect))
                return null;

            string[] parts = cookCollect.Split(new string[] { ",  "}, StringSplitOptions.RemoveEmptyEntries);

            return parts;
        }
    }
}
